<template>
	<div class="pok-tool-bar2">
		<section v-if="taskTypeEnum.DoneTask === taskType" style="height: 32px">
			<slot name="bidButton"></slot>
		</section>
		<section class="left-block">
			<div v-if="taskTypeEnum.Drafts === taskType">
				<a-button
					type="primary"
					:disabled="!selectedRows.length"
					@click="handleDeleteDrafts"
				>
					{{ iTrans('pages.process.deleteSelect', '删除选中项') }}
				</a-button>
			</div>
			<template v-else-if="selectedRows.length">
				<div class="selected">
					<a-avatar :size="28" class="avatar-clear" @click="handleClearSelect">
						<i class="low-code iconcuo clear-icon"></i>
					</a-avatar>
					{{
						iTrans(
							'pages.process.select.selected',
							`已选表单 ${selectedRows.length}`,
							{ count: selectedRows.length }
						)
					}}
				</div>
			</template>
			<section
				v-show="!selectedRows.length && taskTypeEnum.Drafts !== taskType"
				style="display: flex; align-items: center"
			>
				<section
					v-show="!selectedRows.length && taskTypeEnum.AgentTodo === taskType"
					style="display: flex"
				>
					<DropCheckSkeleton
						v-if="taskLoading"
						style="width: 236; height: 32"
					/>
					<!-- 委托人选择 -->
					<drop-checkbox
						v-else
						class="task-type"
						:check-options="checkAgentOptions"
						:check-data="checkAgentDataRef"
						:check-total="checkAgentTotalRef"
						:disabled="isRequesting"
						:isChangeLayout="isChangeLayout"
						:taskType="taskType"
						:isAgentCheck="isAgentCheck"
						@getCheckData="getAgentCheckData"
						:placeholder="iTrans('placeholder.select', '请选择')"
						:tag-render="
							!checkAgentDataRef ||
							checkAgentDataRef.length >= checkAgentOptions.length
								? iTrans(
										'pages.process.select.allAgents',
										`${checkAgentTotalRef.text}`
								  )
								: iTrans(
										'component.state.checked',
										`已选 ${checkAgentDataRef.length} 项`,
										{
											count: checkAgentDataRef.length,
										}
								  )
						"
						@on-blur="handleUpdateAgent"
					/>
				</section>
				<DropCheckSkeleton
					v-if="taskSelect[taskType]?.length && taskLoading"
					style="width: 236; height: 32"
				/>
				<!-- 审批、知会等类型选择 -->
				<a-select
					v-else-if="
						taskSelect[taskType]?.length && isShowSelect && !isChangeLayout
					"
					v-model:value="selectTypeRef"
					style="width: 200px; margin-right: 8px"
					:placeholder="iTrans('placeholder.select', '请选择')"
					dropdown-class-name="tool-select"
					:disabled="isRequesting"
					@change="handleChangeType"
				>
					<template #suffixIcon>
						<i class="low-code iconpackup" />
					</template>
					<!-- {{ taskTypeTodoTask }} -->
					<a-select-option
						v-for="item in taskOptions"
						:key="item?.value"
						:value="item?.value"
					>
						<div class="select-option">
							<span class="select-option-text">{{ item?.text }}</span>
							<span v-if="item.count" class="select-option-count">
								{{ item?.count }}
							</span>
						</div>
					</a-select-option>
				</a-select>
				<a-button
					v-if="
						taskType === 'TaskNotice' &&
						selectTypeRef === 'todo' &&
						selectCountRef >= 0
					"
					type="primary"
					style="margin-right: 20px"
					:disabled="selectCountRef === 0"
					@click="checkAllRead"
				>
					{{ iTrans('personalCenter.allReadBtn', '全部标记为已读') }}
				</a-button>
			</section>
		</section>
		<section class="right-block" v-if="!isChangeLayout">
			<div v-show="!selectedRows.length || taskTypeEnum.Drafts === taskType">
				<input-search
					ref="inputSearch"
					:search-placeholder="searchPlaceholder"
					:task-type="taskType"
					style="width: 384px"
					:done-type="doneType"
					@search="onSearch"
				></input-search>
			</div>
			<div v-show="selectedRows.length && taskTypeEnum.Drafts !== taskType">
				<a-space :size="12">
					<a-button type="primary" @click="handleAgree">{{
						iTrans('common.agree', '同意')
					}}</a-button>
				</a-space>
			</div>
		</section>
	</div>
</template>

<script setup lang="ts">
import { ref, unref, watch, createVNode, computed, onMounted } from 'vue'
import type { Ref } from 'vue'
import { Modal } from 'ant-design-vue'
import { useStore } from 'vuex'
import { debounce } from 'lodash'
import { QuestionCircleOutlined } from '@ant-design/icons-vue'
import { i18n } from '@/locales'
import InputSearch from '@/entry_desktop/components/InputSearch/index.vue'
import { taskTypeEnum, doneTaskEnum } from '@/constant/enums/processCenter'
import { taskSelect } from './constant/task'
import { DropCheckSkeleton } from './skeleton'
import './index.vue'
const { $t: iTrans, locale } = i18n

const props = defineProps<{
	selectedRows: Recordable<any>[]
	taskType: keyof typeof taskTypeEnum
	cacheData: Recordable<any>
	taskLoading: boolean
	agreePromise?: (resolve: any, reject: any) => void
	batchPromise?: () => void
	deletePromise?: (
		draftIds: string[],
		resolve?: any,
		reject?: any
	) => Promise<void>
	checkOptions: []
	checkData: []
	checkTotal: Recordable<any>
	checkAgentOptions: []
	checkAgentData: []
	checkAgentTotal: Recordable<any>
	applyCount: Recordable<any>
	doneType: string
	isRequesting: boolean
	isChangeLayout: boolean
	selectTypeList: string[]
	isResetVal: boolean
	selectTypeStatus: any
}>()
const emit = defineEmits(['onClearSelect', 'onSearch', 'getSelectType'])
const subjectRef = ref('')
const inputSearch = ref()
const extraParamRef: Ref<Recordable<any>> = ref({})
const selectTypeRef = ref('approve')
const selectCountRef = ref(0)
const searchPlaceholder = computed(() => {
	let placeholder = ''
	if (props.taskType === taskTypeEnum.Drafts) {
		placeholder = iTrans('pages.process.search.draftsPlaceholder', '流程名称')
	} else if (props.taskType === taskTypeEnum.Apply) {
		placeholder = iTrans(
			'pages.process.search.applyPlaceholder',
			'流程名称、任务主题'
		)
	} else if (props.taskType === taskTypeEnum.ExpactTask) {
		placeholder = iTrans(
			'pages.process.search.expactTaskPlaceholder',
			'流程名称、任务主题、申请人、当前负责人'
		)
	} else {
		placeholder = iTrans(
			'pages.process.search.placeholder',
			'流程名称、任务主题、申请人'
		)
	}
	return placeholder
})
// 全部流程select
const checkDataRef: any = ref([])
const checkTotalRef: Ref<Recordable<any>> = ref({})

// 全部委托人
const checkAgentDataRef: any = ref([])
const checkAgentTotalRef: Ref<Recordable<any>> = ref({})

// 申请人option
const taskOptions: any = ref([])
const isShowSelect: any = ref(false)

// 区分 全部委托 和 全部流程 组件
const isAgentCheck = ref(true)
//左右布局 获取委托人选中数据
const getAgentCheckData = (val: any) => {
	checkAgentDataRef.value = val
}
watch(
	() => props.doneType,
	() => {
		selectTypeRef.value = ''
	}
)

watch(
	[() => props.applyCount, () => props.isChangeLayout],
	(value, old) => {
		isShowSelect.value = false
		setTimeout(() => {
			if (props.taskType === 'DoneTask') {
				taskOptions.value = taskSelect[props.taskType]?.map(item => {
					item.count = 0
					for (let key in props.applyCount) {
						if (item.value === props.applyCount[key].command_type) {
							item.count = props.applyCount[key].count
						}
					}
					return item
				})
				// .filter(item => item.count > 0 || item.value === '')
			} else {
				taskOptions.value = taskSelect[props.taskType]?.map(item => {
					if (
						['approve', 'all', 'complete', 'termination'].includes(
							item.value
						) ||
						item.value === 'todo'
					) {
						if (item.value === 'approve') {
							item.count = props.applyCount.approve_count
						} else if (item.value === 'all') {
							item.count = props.applyCount.sum_count
						} else if (item.value === 'complete') {
							item.count = props.applyCount.complete_count
						} else if (item.value === 'termination') {
							item.count = props.applyCount.termination_count
						} else {
							item.count = props.applyCount.un_read_count
							selectCountRef.value = props.applyCount.un_read_count
						}
					}
					return item
				})
			}
			isShowSelect.value = true
		})
	},
	{ deep: true, immediate: true }
)

watch(
	() => props.taskType,
	(value, prevValue) => {
		if (value !== prevValue) {
			// 右上方input重新赋值
			subjectRef.value = props.cacheData?.[value]?.subject ?? ''

			// 左上方全部流程select重新赋值
			checkDataRef.value = props.checkData
			checkTotalRef.value = props.checkTotal

			// 全部委托人select重新赋值
			checkAgentDataRef.value = props.checkAgentData
			checkAgentTotalRef.value = props.checkAgentTotal

			// 审批人
			if (props.taskType === taskTypeEnum.Apply) {
				selectTypeRef.value =
					taskSelect[unref(value) as keyof typeof taskSelect]?.[1]?.value
			}
			// 我的已办
			if (props.taskType === taskTypeEnum.DoneTask) {
				selectTypeRef.value =
					taskSelect[unref(value) as keyof typeof taskSelect]?.[0]?.value
			}
			// 我的知会
			if (taskTypeEnum.TaskNotice === unref(props.taskType)) {
				selectTypeRef.value =
					taskSelect[unref(value) as keyof typeof taskSelect]?.[0]?.value
				selectCountRef.value =
					taskSelect[unref(value) as keyof typeof taskSelect]?.[0]?.count
			}
		}
	},
	{
		immediate: true,
	}
)
watch(
	() => selectTypeRef.value,
	(val: any) => {
		emit('getSelectType', val)
	}
)
watch(
	() => props.isResetVal,
	() => {
		// 审批人
		if (props.taskType === taskTypeEnum.Apply) {
			selectTypeRef.value =
				taskSelect[unref(props.taskType) as keyof typeof taskSelect]?.[1]?.value
		}
		// 我的已办
		if (props.taskType === taskTypeEnum.DoneTask) {
			selectTypeRef.value =
				taskSelect[unref(props.taskType) as keyof typeof taskSelect]?.[0]?.value
		}
		// 我的知会
		if (taskTypeEnum.TaskNotice === unref(props.taskType)) {
			selectTypeRef.value =
				taskSelect[unref(props.taskType) as keyof typeof taskSelect]?.[0]?.value
			selectCountRef.value =
				taskSelect[unref(props.taskType) as keyof typeof taskSelect]?.[0]?.count
		}
	}
)
// 全部流程select option数据监听
watch(
	() => props.checkOptions,
	(value, prevValue) => {
		checkDataRef.value = checkDataRef.value.filter((item: any) => {
			return value.find((x: any) => x.value == item)
		})
	}
)
watch(
	() => props.checkAgentOptions,
	(value, prevValue) => {
		if (!checkAgentDataRef.value.length) {
			// 无一选中情况
			checkAgentDataRef.value = value.map((item: any) => item.value)
		}
	}
)
watch(
	() => props.checkData,
	(val: any) => {
		if (!val.length) {
			// 无一选中情况
			checkDataRef.value = props.checkOptions.map((item: any) => item.value)
		} else {
			checkDataRef.value = val
		}
	}
)
const handleUpdateAgent = (value: string) => {
	const list: any = props.checkAgentOptions?.map((item: any) => item.value)
	if (!value.length) {
		//如果取消选中，则重新赋值为默认全选
		checkAgentDataRef.value = list
		checkAgentTotalRef.value = props.checkAgentTotal
	} else {
		checkAgentDataRef.value = value
	}
	handleUpdateList()
}

const handleClearSelect = () => {
	emit('onClearSelect')
}
const handleUpdateList = debounce((type = '') => {
	let selectTypeLocalVal = ''
	if (taskTypeEnum.Apply === unref(props.taskType)) {
		selectTypeLocalVal = selectTypeRef.value
	}
	let noticeType = ''
	if (taskTypeEnum.TaskNotice === unref(props.taskType)) {
		noticeType = selectTypeRef.value
	}
	let commandType = ''
	if (taskTypeEnum.DoneTask === unref(props.taskType)) {
		commandType = selectTypeRef.value
	}
	if (!props.isChangeLayout) {
		checkDataRef.value = props.selectTypeList
	}
	let typeKeyList = checkDataRef?.value?.join(',') || ''
	if (props.checkOptions.length === checkDataRef?.value?.length) {
		typeKeyList = ''
	}
	emit(
		'onSearch',
		Object.assign(
			{
				subject: subjectRef,
				type_key_list: typeKeyList,
				agent_id: checkAgentDataRef?.value?.join(','),
				total_count_data: checkTotalRef,
				agent_id_total: checkAgentTotalRef,
			},
			{
				status: selectTypeLocalVal,
				type: noticeType,
				command_type: commandType,
			}
		),
		type
	)
}, 500)

// 搜索
const onSearch = debounce((value: string) => {
	subjectRef.value = value
	handleUpdateList()
}, 800)
const handleChangeType = () => {
	extraParamRef.value = {}
	// 后续优化
	if (taskTypeEnum.Apply === unref(props.taskType)) {
		unref(extraParamRef)['status'] = unref(selectTypeRef)
	}
	if (taskTypeEnum.TaskNotice === unref(props.taskType)) {
		unref(extraParamRef)['type'] = unref(selectTypeRef)
	}
	if (taskTypeEnum.DoneTask === unref(props.taskType)) {
		unref(extraParamRef)['type'] = unref(selectTypeRef)
	}
	handleUpdateList()
}

const handleAgree = () => {
	Modal.confirm({
		title: iTrans(
			'pages.process.agreeTip',
			`是否同意 ${props.selectedRows.length} 条审批任务？`,
			{ count: props.selectedRows.length }
		),
		okText: iTrans('personalCenter.confirm', '确认'),
		cancelText: iTrans('personalCenter.cancel', '取消'),
		icon: createVNode(QuestionCircleOutlined),
		onOk() {
			return new Promise((resolve, reject) => {
				if (props.agreePromise) {
					props.agreePromise(resolve, reject)
				} else {
					reject()
				}
			})
		},
	})
}

const handleDeleteDrafts = () => {
	Modal.confirm({
		title: iTrans('pages.process.batchDeleteTip', `确定删除已选中的表单？`),
		icon: createVNode(QuestionCircleOutlined),
		okText: iTrans('common.confirm', '确认'),
		cancelText: iTrans('common.cancel', '取消'),
		onOk() {
			return new Promise((resolve, reject) => {
				if (props.deletePromise) {
					props.deletePromise(
						props.selectedRows.map(item => item.draft_id),
						resolve,
						reject
					)
				} else {
					reject()
				}
			})
		},
	})
}

const clearParentInput = (value: any) => {
	unref(unref(inputSearch)?.clearInput())
}

// 全部标记为已读 button
const checkAllRead = () => {
	Modal.confirm({
		title: iTrans(
			'pages.process.allReadTip',
			`确认将 ${selectCountRef.value} 条知会标记为已读？`,
			{ count: selectCountRef.value }
		),
		icon: createVNode(QuestionCircleOutlined),
		centered: true,
		okText: iTrans('common.confirm', '确认'),
		cancelText: iTrans('common.cancel', '取消'),
		onOk() {
			if (props.batchPromise) {
				props.batchPromise()
			}
		},
	})
}
onMounted(() => {
	selectTypeRef.value = props.selectTypeStatus
})

defineExpose({
	subjectRef,
	selectTypeRef,
	checkDataRef,
	checkTotalRef,
	clearParentInput,
})
</script>
<style lang="less" scoped>
.right-block {
	display: flex;
	justify-content: flex-end;
	width: 100%;
}
.pok-tool-bar2 {
	display: flex;
	align-items: center;
	padding-top: 20px;
	// margin-right: 16px;
	padding-bottom: 16px;
	.left-block {
		display: flex;
		flex: 1;
		height: 100%;
		width: 100%;
		// margin-left: 15px;

		.iconshanchutou-zhankai {
			font-size: 14px;
			color: @rok-auxiliary-color;
		}

		.iconpackup {
			font-size: 14px;
			color: @rok-auxiliary-color;
			transition: all 0.3s ease 0.1s;
		}

		.ant-select-open {
			.iconpackup {
				transform: rotate(-180deg);
			}
		}

		.task-type {
			// margin-right: 16px;

			.ant-select-selector {
				.ant-select-selection-item:first-child {
					max-width: 135px;

					.ant-select-selection-item-content {
						& > div {
							display: inline;
						}
					}
				}
			}
		}

		.selected {
			display: flex;
			align-items: center;
			font-size: 14px;
			color: @rok-text-color;
			font-weight: @rok-font-weight-bold;
			width: 140px;

			.avatar-clear {
				margin-right: 12px;
				background-color: @rok-label-bg-color;
				cursor: pointer;

				.clear-icon {
					font-size: 28px;
					color: @rok-primary-color;
				}

				&:hover {
					background-color: @rok-primary-color;

					.clear-icon {
						color: @rok-white-color;
					}
				}
			}
		}
	}
}
</style>
